import React, { useState, useEffect } from 'react'
import { Layout, Drawer } from 'antd'
import { Outlet } from 'react-router-dom'
import Header from '@/components/layout/Header'
import Sidebar from '@/components/layout/Sidebar'
import Footer from '@/components/layout/Footer'
import Breadcrumb from '@/components/common/Breadcrumb'

const { Content } = Layout

const MainLayout: React.FC = () => {
  const [collapsed, setCollapsed] = useState(false)
  const [isMobile, setIsMobile] = useState(false)
  const [drawerVisible, setDrawerVisible] = useState(false)

  useEffect(() => {
    const handleResize = () => {
      const mobile = window.innerWidth < 768
      console.log('MainLayout: Window width:', window.innerWidth, 'isMobile:', mobile)
      setIsMobile(mobile)
      if (!mobile) {
        setDrawerVisible(false)
      }
    }

    handleResize()
    window.addEventListener('resize', handleResize)
    return () => window.removeEventListener('resize', handleResize)
  }, [])

  useEffect(() => {
    console.log('MainLayout: drawerVisible changed to:', drawerVisible)
  }, [drawerVisible])

  const handleMenuClick = () => {
    console.log('MainLayout: Menu clicked, current drawerVisible:', drawerVisible)
    setDrawerVisible(true)
    console.log('MainLayout: setDrawerVisible(true) called')
  }

  const handleDrawerClose = () => {
    console.log('MainLayout: Drawer closing')
    setDrawerVisible(false)
  }

  return (
    <Layout className="min-h-screen">
      <Header onMenuClick={handleMenuClick} />
      <Layout style={{ marginTop: 64 }}>

        {/* Desktop sidebar */}
        {!isMobile && (
          <Sidebar collapsed={collapsed} onCollapse={setCollapsed} />
        )}

        {/* Mobile drawer */}
        {isMobile && (
          <Drawer
            placement="left"
            closable={true}
            onClose={handleDrawerClose}
            open={drawerVisible}
            width={280}
            bodyStyle={{ padding: 0 }}
            zIndex={9999}
            getContainer={false}
            styles={{
              mask: { backdropFilter: 'blur(2px)' },
              wrapper: { position: 'absolute' }
            }}
            rootStyle={{ position: 'absolute' }}
          >
            <Sidebar collapsed={false} onCollapse={handleDrawerClose} />
          </Drawer>
        )}

        <Layout 
          className="bg-gray-50 transition-all duration-200"
          style={{ 
            marginLeft: isMobile ? 0 : (collapsed ? 80 : 200), 
            minHeight: 'calc(100vh - 64px)' 
          }}
        >
          <div className="p-2 sm:p-4 bg-white border-b">
            <Breadcrumb />
          </div>
          <Content className="m-2 sm:m-4 p-3 sm:p-6 bg-white rounded-lg min-h-[280px]">
            <Outlet />
          </Content>
          <Footer />
        </Layout>
      </Layout>
    </Layout>
  )
}

export default MainLayout